package util

import (
	"errors"
	"net"
	"reflect"
)

func Int2Str(seq uint64) (str string) {
	s := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
	len := uint64(len(s))

	charSeq := []rune{}
	if seq != 0 {
		for seq != 0 {
			mod := seq % len
			div := seq / len

			charSeq = append(charSeq, rune(s[mod]))
			seq = div
		}
	} else {
		charSeq = append(charSeq, rune(s[seq]))
	}

	str = string(charSeq)
	return Reverse(str)
}

func Reverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

func InSlice(val interface{}, arr interface{}) bool {
	slice, err := Sliceconv(arr)
	if err != nil {
		return false
	}

	for _, item := range slice {
		if item == val {
			return true
		}
	}

	return false
}

func Sliceconv(slice interface{}) ([]interface{}, error) {
	v := reflect.ValueOf(slice)
	if v.Kind() != reflect.Slice {
		return nil, errors.New("warning: sliceconv: param \"slice\" should be on slice value")
	}

	l := v.Len()
	r := make([]interface{}, l)
	for i := 0; i < l; i++ {
		r[i] = v.Index(i).Interface()
	}
	return r, nil
}

func GetIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}
